#include "userdao.h"
#include"../utils/database.h"
#include"QSqlQuery"
#include<QSqlRecord>
#include<QVariant>
#include<QSqlError>
#include<QDebug>


UserDao::UserDao()
{
    QSqlQuery result=QSqlQuery(*DataBase::getInstance());
}

bool UserDao::getUser(User &user)
{
    QString sql=("select * from User where phone = '%1';");
    sql=sql.arg(QString::fromStdString(user.phone));
    bool count=result.exec(sql);
    if(!count)
    {
        qDebug()<<result.lastError().text();
        qDebug()<<sql;
        return false;
    }
    if(!result.next())
        return false;
    user.password=result.value("password").toString().toStdString();
    user.type=result.value("type").toInt();
    user.identityCard=result.value("identityCard").toString().toStdString();
    user.name=result.value("name").toString().toStdString();
    user.sex=result.value("sex").toString().toStdString();
    user.creditCard=result.value("creditCard").toString().toStdString();
    return true;
}

bool UserDao::insertUser(User &user)
{
    QString sql="insert into User(phone,password,type,identityCard,name,"
                "sex,creditCard) value('%1','%2',%3,'%4','%5','%6','%7');";
    sql=sql.arg(QString::fromStdString(user.phone))
           .arg(QString::fromStdString(user.password))
           .arg(user.type)
           .arg(QString::fromStdString(user.identityCard))
           .arg(QString::fromStdString(user.name))
           .arg(QString::fromStdString(user.sex))
           .arg(QString::fromStdString(user.creditCard));
    if(result.exec(sql))
        return true;
    else
    {
        qDebug()<<result.lastError().text();
    }
    return false;
}

bool UserDao::alterUser(User &user)
{
    QString sql="update User set phone='%1' password='%2' type=%3 identityCard='%4' name='%5' sex='%6' creditCard='%7' where phone = '%8'";
    sql=sql.arg(QString::fromStdString(user.phone))
            .arg(QString::fromStdString(user.password))
            .arg(user.type)
            .arg(QString::fromStdString(user.identityCard))
            .arg(QString::fromStdString(user.name))
            .arg(QString::fromStdString(user.sex))
            .arg(QString::fromStdString(user.creditCard))
            .arg(QString::fromStdString(user.phone));
     if(result.exec(sql))
     {
        return true;
       }
     else
     {
         qDebug()<<result.lastError().text();
     }
     return false;
}

bool UserDao::delUser(User &user)
{
    QString sql="delete from User where phone = '%1'";
    sql=sql.arg(QString::fromStdString(user.phone));
    if(result.exec(sql))
          return true;
    else
    {
        qDebug()<<result.lastError().text();
    }
    return false;
}



